﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuShanTea.Web.Common
{
    public class LuShanTealPager
    {
        /// <summary>
        /// 每页数据条数
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 总数据条数
        /// </summary>
        public long TotalCount { get; set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageIndex { get; set; }

        /// <summary>
        /// 地址格式
        /// </summary>
        public string UrlPattern { get; set; }

        /// <summary>
        /// 显示的最大页数
        /// </summary>
        public int MaxPagerCount { get; set; }

        /// <summary>
        /// 选中li的类名
        /// </summary>
        public string CurrentLinkClassName { get; set; }

        public LuShanTealPager()
        {
            PageSize = 10;
            MaxPagerCount = 10;
        }

        public string GetPager()
        {
            if (TotalCount<= PageSize)
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            int pageCount = (int)Math.Ceiling(TotalCount * 1.0 / PageSize);
            int startPagerIndex = Math.Max(1, PageIndex - MaxPagerCount / 2);
            int endPagerIndex = Math.Min(pageCount, startPagerIndex + MaxPagerCount - 1);

            sb.AppendLine("<ul>");

            for (int i = startPagerIndex; i <= endPagerIndex; i++)
            {
                if (i == PageIndex)
                {
                    sb.Append("<li class=\"").Append(CurrentLinkClassName).Append("\">").Append(i).Append("</li>");
                }
                else
                {
                    sb.Append("<li>").Append("<a href=\"")
                        .Append(UrlPattern.Replace("{pn}", i.ToString()))
                        .Append("\">" + i + "</a>").Append("</li>");
                }
            }

            sb.AppendLine("</ul>");

            return sb.ToString();
        }

    }
}
